﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using System.ComponentModel.DataAnnotations;
using machine_registration.ViewModels;
using machine_registration.Views.Pages;
using System.Windows.Media.Media3D;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using machine_registration.Models;
[Table("borrow_records")]
public partial class BorrowRecord : ObservableValidator
{
    [ObservableProperty]
    public bool _IsSelected; // 新增勾选属性
    /// <summary>
    /// ID 主键
    /// </summary>
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public int BorrowRecordsId { get; set; }
    /// <summary>
    ///外键
    /// </summary>
    public int DeviceInventoryId { get; set; }
    [ForeignKey(nameof(DeviceInventoryId))]
    public virtual DeviceInventory DeviceInventory { get; set; } // 反向导航属性
    /// <summary>
    /// UUID
    /// </summary>
    [Column(TypeName = "TEXT")]
    [StringLength(36)]
    public string Uuid ;
    /// <summary>
    /// SN号
    /// </summary>
    [ObservableProperty]
   // [Required(ErrorMessage = "设备SN不能为空")]
    [RegularExpression(@"^[a-zA-Z0-9]+$", ErrorMessage = "设备ID格式不正确,只能输入纯数字和字母）")]
    private string _machineId = string.Empty; 
    /// <summary>
    /// 编号
    /// </summary>
    [ObservableProperty]
    [StringLength(50, ErrorMessage = "序列号长度不能超过50个字符")]
    private string? _SerialNumber;
    /// <summary>
    /// 实际归属人
    /// </summary>
    [ObservableProperty]
    public string? _OwnerId=string.Empty;
    /// <summary>
    /// 借出日期
    /// </summary>
    [ObservableProperty]
    [Required(ErrorMessage = "必须选择借出日期")]
    [CustomValidation(typeof(BorrowRecord), nameof(ValidateBorrowDate))]
    private DateTime _BorrowDate = DateTime.Now;
    /// <summary>
    /// 预计归还日期
    /// </summary>
    [ObservableProperty]
    [Required(ErrorMessage = "必须填写预计归还日期")]
    [CustomValidation(typeof(BorrowRecord), nameof(ValidateReturnDate))]
    private DateTime? _ExpectedReturnDate= DateTime.Now.AddDays(3);
    /// <summary>
    /// 实际归还日期
    /// </summary>
    [ObservableProperty]
    private DateTime? _ActualReturnDate;
    /// <summary>
    /// 对方信息 (借用人)
    /// </summary>
    [ObservableProperty]
    [Required(ErrorMessage = "对方信息不能为空")]
    [StringLength(100, MinimumLength = 1, ErrorMessage = "名称长度需在1-100个字符之间")]
    private string _Counterpart = string.Empty;
    /// <summary>
    /// 数量
    /// </summary>
    [ObservableProperty]
    [Range(1, 100, ErrorMessage = "数量需在1-100之间")]
    private int _quantity = 1;

    /// <summary>
    /// 设备类型
    /// </summary>
    [ObservableProperty]
    [Required(ErrorMessage = "必须选择设备类型")]
    private DeviceType _deviceType;
    /// <summary>
    /// 设备名称
    /// </summary>
    [ObservableProperty]
    [Required(ErrorMessage = "设备名称不能为空")]
    [StringLength(100)]
    public string _DeviceName = string.Empty;
    /// <summary>
    /// 设备使用状态 (在库可借,已借出,等待归还,归还完成,维护中,已报废)
    /// </summary>
    [ObservableProperty]
    [Required]
    public InventoryStatus _Status;


    /// <summary>
    /// 备注
    /// </summary>
    [ObservableProperty]
    [StringLength(5000, ErrorMessage = "备注最多5000个字符")]
    private string? _notes;

    /// <summary>
    /// 设备可用状态 是否已经归还工厂,默认为false
    /// </summary>
    [ObservableProperty]
    public bool _Isfactory =false;
    /// <summary>
    /// 录入系统时间
    /// </summary>
    [ObservableProperty]
    private DateTime _CreatedAt = DateTime.Now;
    /// <summary>
    /// 系统最后一次更新时间
    /// </summary>
    [ObservableProperty]
    private DateTime  _UpdatedAt = DateTime.Now;



    // 自定义验证规则：借出日期
    public static ValidationResult ValidateBorrowDate(DateTime borrowDate, ValidationContext context)
    {
        var record = (BorrowRecord)context.ObjectInstance;

        if (borrowDate > DateTimeOffset.Now)
            return new("借出日期不能晚于当前时间", [nameof(BorrowDate)]);

        return ValidationResult.Success!;
    }

    // 自定义验证规则：归还日期
    public static ValidationResult ValidateReturnDate(DateTime? returnDate, ValidationContext context)
    {
        var record = (BorrowRecord)context.ObjectInstance;

        if (returnDate < record.BorrowDate)
            return new("预计归还日期不能早于借出日期", [nameof(ExpectedReturnDate)]);

        return ValidationResult.Success!;
    }

 
    /// <summary>
    ///   Model 层验证
    /// </summary>
    /// <param name="value"></param>
    public (bool isok,string erro) ValidateProperties()
    {

        // 触发 Record 模型验证
        ValidateAllProperties();

        // 合并错误信息
        var errors = new List<string>();

        if (HasErrors)
        {
            errors.AddRange(GetErrors().Select(e => e.ErrorMessage));
        }

  

        // 显示错误
        if (errors.Count > 0)
        {
          
            return (false, string.Join(",", errors)); 
        }
        return (true, "");
    }

    // 自动更新时间戳（通过局部方法扩展）
    partial void OnMachineIdChanging(string value) => UpdateTimestamp();
    partial void OnSerialNumberChanging(string? value) => UpdateTimestamp();
    //partial void OnBorrowDateChanging(DateTime? value) => UpdateTimestamp();
    partial void OnExpectedReturnDateChanging(DateTime? value) => UpdateTimestamp();
    partial void OnCounterpartChanging(string value) => UpdateTimestamp();
    partial void OnQuantityChanging(int value) => UpdateTimestamp();
    partial void OnDeviceTypeChanging(DeviceType value) => UpdateTimestamp();
    partial void OnNotesChanging(string? value) => UpdateTimestamp();

    private void UpdateTimestamp() => UpdatedAt = DateTime.Now;
}

